<?php
namespace Member\Controller;

class ApplistController extends MemberController {
	
	function index() {
		$map['uid'] = UID;
		$list = M('WechatApp')->where($map)->select();
		$this->assign('__LIST__', $list);
		$this->title('我的公众号');
		$this->display();
	}

	function add() {
		if (IS_POST) {
			$model = D('WechatApp');
			if (!$model->create()) {
				$this->error($model->getError());
			}else {
				$appid = $model->add();
				if ($appid) {
					D('WechatQuota')->init($appid);
					D('WebSite')->init($appid);
					$this->success('保存成功！', U('index'));
				}else {
					$this->error('保存失败！');
				}
			}
		}else {
			$this->title('添加公众号');
			$this->display('edit');
		}
	}
	
	function edit($appid) {
		if (IS_POST) {
			$model = D('WechatApp');
			if (!$model->create()) {
				$this->error($model->getError());
			}else {
				if ($model->save()) {
					$this->success('保存成功！', U('index'));
				}else {
					$this->error('保存失败！');
				}
			}
		}else {
			$info = $this->oFind('WechatApp', $appid);
			$this->assign('info', $info);
			$this->title('编辑公众号');
			$this->display();
		}
	}
	
	function del($appid) {
		if (IS_POST) {
			$password = I('post.password');
			$username = session('user_auth.username');
			empty($password) && $this->error('密码不能为空！');
			//验证用户名 密码
			$Api = new \User\Api\UserApi;
			$uid = $Api->login($username, $password);
			if ($uid > 0) {
				$model = M('WechatApp');
				$this->oFind('WechatApp', $appid);
				if ($model->delete($appid)) {
					$this->success('删除公众号成功！', U('/Member/Applist'));
				}else {
					$this->error('删除公众号失败！');
				}
			}else {
				$this->error('账户密码不正确！');
			}
		}else {
			$this->title('删除公共号');
			$this->display();
		}
	}
	
	function api($appid) {
		$info = $this->oFind('WechatApp', $appid);
		$url  = 'http://'.$_SERVER['HTTP_HOST'].'/wechat.php?appid='.$appid;
		$this->assign('appName', $info['title']);
		$this->assign('url', $url);
		$this->assign('token' ,$info['token']);
		$this->display();
	}
}